package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.KaptchaCodeRequest;
import com.cskaoyan.user.dto.KaptchaCodeResponse;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * @author sosog
 * @version 1.0.0
 * @description TODO
 * @date 2022/6/17 21:28
 */
@Slf4j
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    IKaptchaService iKaptchaService;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest request, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        UserLoginResponse response = new UserLoginResponse();
        // 1.验证验证码
        String captcha = request.getCaptcha();
        if (!checkCaptcha(captcha, servletRequest)) {
            log.info("验证码错误");
            response.setCode(UserRetCode.KAPTCHA_CODE_ERROR.getCode());
            response.setMsg(UserRetCode.KAPTCHA_CODE_ERROR.getMessage());
            return response;
        }
        // 2.验证用户名以及密码
        // 密码需要加密后验证
        String password = DigestUtils.md5DigestAsHex(request.getPassword().getBytes());

        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username", request.getUserName())
                .andEqualTo("password", password);
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)) {
            log.info("用户名或密码错误");
            response.setCode(UserRetCode.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            return response;
        }
        Member user = members.get(0);
        if (StringUtils.equals(user.getIsVerified(), "N")) {
            log.info("用户尚未激活");
            response.setCode(UserRetCode.USER_ISVERFIED_ERROR.getCode());
            response.setMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
            return response;
        }
        // 3.产生一个合法的JWT
        HashMap<String, String> map = new HashMap<>();
        map.put("username", request.getUserName());
        map.put("uid", user.getId().toString());
        String msg = JSON.toJSONString(map);
        // 产生jwt的token
        String token = JwtTokenUtils.builder().msg(msg).build().creatJwtToken();
        // 将token放入cookie中
        Cookie cookie = new Cookie("access_token", token);
        cookie.setPath("/");
//        cookie.setDomain(".localhost:9999");
        cookie.setMaxAge(3600);
        CookieUtil.setCookie(servletResponse, cookie);

        response = userConverterMapper.converter(user);
        response.setState(1);
        response.setToken(token);

        log.info("登录成功");
        response.setCode(UserRetCode.SUCCESS.getCode());
        response.setMsg(UserRetCode.SUCCESS.getMessage());
        return response;
    }

    private boolean checkCaptcha(String captcha, HttpServletRequest servletRequest) {
        String kaptcha_uuid = CookieUtil.getCookieValue(servletRequest, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(captcha);
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = response.getCode();
        return code.equals(SysRetCodeConstants.SUCCESS.getCode());
    }
}
